#pragma once
#ifndef VF_SINK_H
#define VF_SINK_H
#include <vf_pch.h>

namespace VFAdapter {

template <typename TSink> class CEventSink {
public:
  IUnknownPtr m_pUnkCP; // reference to the connection point pointer
  TSink *m_pSink;       // pointer to the sink interface object
  DWORD m_dwCookie;

  CEventSink(TSink *pSink) : m_pSink(pSink), m_dwCookie(0) {}

  ~CEventSink() {
    if (m_dwCookie)
      DisConnect();
  }

  HRESULT Connect(IUnknown* pUnkCP) {
	  try {
		  HRESULT hr;
		  m_pUnkCP = pUnkCP;
		  hr = ATL::AtlAdvise(m_pUnkCP, m_pSink, __uuidof(TSink), &m_dwCookie);
		  ATLASSERT(SUCCEEDED(hr));
		  return S_OK;
	  }
	  catch (_com_error const& e)
	  {
		  return E_FAIL;
	  }

	  return E_FAIL;
  }

  HRESULT DisConnect(void) {
    HRESULT hr = S_OK;
    if (m_dwCookie) {
      hr = ATL::AtlUnadvise(m_pUnkCP, __uuidof(TSink), m_dwCookie);
      m_pUnkCP = NULL;
      ATLASSERT(SUCCEEDED(hr));
      m_dwCookie = 0;
    }
    return hr;
  }
};

} // namespace VFAdapter

#endif